package com.tgu.service.impl;

import com.tgu.entity.model.OrdersEntity;
import com.tgu.entity.model.TrolleyEntity;
import com.tgu.entity.model.UsersEntity;
import com.tgu.entity.request.TrolleyReq;
import com.tgu.entity.request.TrolleyPayReq;
import com.tgu.entity.request.UserCancelReq;
import com.tgu.mapper.OrdersDao;
import com.tgu.mapper.TrolleyDao;
import com.tgu.mapper.UsersDao;
import com.tgu.service.ITrolleyService;
import com.tgu.utils.result.Result;
import com.tgu.utils.result.SystemCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TrolleyServiceImpl implements ITrolleyService {

    @Autowired
    private TrolleyDao trolleyDao;

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private OrdersDao ordersDao;

    @Override
    public Result saveTrolley(TrolleyReq trolleyReq) {
        if (trolleyReq == null) {
            return Result.error(SystemCodeEnum.SYSTEM_SERVER_ERROR);
        }

        // 做手机号校验
        if (!trolleyReq.getOrderPostUserPhone().matches("^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$")
                || !trolleyReq.getOrderAcceptUserPhone().matches("^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$")) {
            return Result.error(SystemCodeEnum.PHONE_NUMBER_ERROR);
        }
        // 做金钱的校验
        if (!trolleyReq.getOrderMoney().matches("\\d+(\\.\\d{1,2})?")) {
            return Result.error(SystemCodeEnum.MONEY_NUMBER_ERROR);
        }

        TrolleyEntity trolleyEntity = new TrolleyEntity();

        trolleyEntity.setInfoDate(new Date());
        trolleyEntity.setAddressAcceptor(trolleyReq.getAddressAcceptor());
        trolleyEntity.setAddressGoods(trolleyReq.getAddressGoods());
        trolleyEntity.setGoodsCode(trolleyReq.getGoodsCode());
        trolleyEntity.setOrderAcceptUserName(trolleyReq.getOrderAcceptUserName());
        trolleyEntity.setOrderPostUserName(trolleyReq.getOrderPostUserName());
        trolleyEntity.setOrderPostUserPhone(trolleyReq.getOrderPostUserPhone());
        trolleyEntity.setOrderAcceptUserPhone(trolleyReq.getOrderAcceptUserPhone());
        trolleyEntity.setOrderRemark(trolleyReq.getOrderRemark());
        trolleyEntity.setOrderMoney(Long.parseLong(trolleyReq.getOrderMoney()));
        trolleyEntity.setUserId(trolleyReq.getUserId());

        int insert = trolleyDao.insert(trolleyEntity);

        if (insert == 0) {
            return Result.error(SystemCodeEnum.INSERT_TROLLEY_ERROR);
        }

        return Result.error(SystemCodeEnum.INSERT_TROLLEY_SUCCESS);
    }

    @Override
    public Result getTrolleyById(String userId) {
        List<TrolleyEntity> trolleys = trolleyDao.getForUserByMybatis(userId);

        if (trolleys == null) {
            return Result.error(SystemCodeEnum.SYSTEM_SERVER_ERROR);
        }

        return Result.ok(SystemCodeEnum.SELECT_SUCCESS).setData(trolleys);
    }

    @Override
    public Result deleteTrolleyById(UserCancelReq deleteReq) {

        UsersEntity usersEntity = usersDao.selectById(deleteReq.getUserId());
        if (usersEntity == null) {
            return Result.error(SystemCodeEnum.LOGIN_TIME_OUT);
        }

        // 内容复用一下UserCancelReq，Trolley表里本没有orderId，否则类似功能的Req类太多了
        int i = trolleyDao.deleteById(deleteReq.getOrderId());
        if (i == 0) {
            return Result.error(SystemCodeEnum.ORDER_NOT_EXIST);
        }

        return Result.ok(SystemCodeEnum.TROLLEY_DELETE_SUCCESS);
    }

    @Override
    @Transactional
    public Result payByUserId(TrolleyPayReq payReq) {

        UsersEntity usersEntity = usersDao.selectById(payReq.getUserId());
        if (usersEntity == null) {
            return Result.error(SystemCodeEnum.LOGIN_TIME_OUT);
        }

        List<TrolleyEntity> trolleyEntities = trolleyDao.selectBatchIds(payReq.getIds());
        if (trolleyEntities == null) {
            return Result.error(SystemCodeEnum.ORDER_NOT_EXIST);
        }

        Long sum = new Long(0);
        List<OrdersEntity> orders = new ArrayList<>();
        for (TrolleyEntity trolleyEntity : trolleyEntities) {
            sum += trolleyEntity.getOrderMoney();

            OrdersEntity order = new OrdersEntity();
            order.setUserId(trolleyEntity.getUserId());
            order.setOrderRemark(trolleyEntity.getOrderRemark());
            order.setOrderMoney(trolleyEntity.getOrderMoney());
            order.setOrderPostUserName(trolleyEntity.getOrderPostUserName());
            order.setOrderPostUserPhone(trolleyEntity.getOrderPostUserPhone());
            order.setOrderPostTime(new Date());
            order.setOrderAcceptUserName(trolleyEntity.getOrderAcceptUserName());
            order.setOrderAcceptUserPhone(trolleyEntity.getOrderAcceptUserPhone());
            order.setAddressGoods(trolleyEntity.getAddressGoods());
            order.setAddressAcceptor(trolleyEntity.getAddressAcceptor());
            order.setGoodsCode(trolleyEntity.getGoodsCode());
            order.setInfoDate(new Date());
            orders.add(order);
        }

        if (usersEntity.getUserMoney() < sum) {
            return Result.error(SystemCodeEnum.MONEY_NOT_ENOUGH);
        }

        usersEntity.setUserMoney(usersEntity.getUserMoney() - sum);
        int i = usersDao.updateById(usersEntity);
        if (i == 0) {
            return Result.error(SystemCodeEnum.SYSTEM_SERVER_ERROR);
        }

        for (OrdersEntity order : orders) {
            ordersDao.insert(order);
        }

        int i1 = trolleyDao.deleteBatchIds(payReq.getIds());
        if (i1 != payReq.getIds().size()) {
            return Result.error(SystemCodeEnum.SYSTEM_SERVER_ERROR);
        }

        return Result.ok(SystemCodeEnum.PAY_SUCCESS);
    }
}
